package com.java2104.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Controller
public class FileUploadController {
    //上传的图片保存的服务器路径
    private static  final String UPLOAD_PATH="D:/javaee/";
    @RequestMapping("/upload")
    @ResponseBody
    public Map upload(@RequestParam("faceImg") MultipartFile multipart) throws IOException {
      String oldFilename=multipart.getOriginalFilename();//获取其原来的文件名如 x.jpx
      long size=multipart.getSize();//获取图片的大小以字节为单位
      InputStream is= multipart.getInputStream();//输入流
      String contentType=multipart.getContentType();//获取上传文件的格式

        if (!new File(UPLOAD_PATH).exists()){//如果保存上传图片的文件目录不存在
            new File(UPLOAD_PATH).mkdirs();//新建这个文件夹目录
        }
        FileOutputStream fos=new FileOutputStream(UPLOAD_PATH+oldFilename);
        // FileCopyUtils.copy()
        FileCopyUtils.copy(is,fos);//将上传文件保存到指定位置
        Map map =new HashMap();
        map.put("filename",oldFilename);
        map.put("size",size);
        map.put("contentType",contentType);
        map.put("status","ok");
        map.put("accessPath","<a href='/image/"+oldFilename+"'>查看图片</a>");
        return  map;
    }
    @GetMapping("/upload")
    public  String upload(){
        return  "fileupload";
    }
    @GetMapping("/image/{filename}")
    public void fileDownload(@PathVariable("filename") String filename,
                             HttpServletRequest req,
                             HttpServletResponse resp) throws IOException {
        String uri=req.getRequestURI();// /image/lbxx.jpg
        String suffix=req.getRequestURI().substring(uri.lastIndexOf("."));//.jpg
        //获取访问文件的输出流
        FileInputStream fis=new FileInputStream(UPLOAD_PATH+filename+suffix);
        FileCopyUtils.copy(fis,resp.getOutputStream());

    }
}
